package com.gmail.bloim.serg.testrunner;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * User: Администратор
 * Date: 25.04.13
 * Time: 14:15
 */
public class AccumulateTestResultHandler extends StubTestResultHandler {
    List<Test> success = new ArrayList<Test>();
    List<Test> failure = new ArrayList<Test>();
    Map<Test, Throwable> exception = new LinkedHashMap<Test, Throwable>();
    TestTimeRegistrator timeRegistrator = new TestTimeRegistrator();

    @Override
    public void onTestSuccess(Test test) {
        onTestFinish(test);
        success.add(test);
    }

    @Override
    public void onTestFail(Test test) {
        onTestFinish(test);
        failure.add(test);
    }

    @Override
    public void onTestException(Test test, Throwable e) {
        onTestFinish(test);
        exception.put(test, e);
    }

    public void printTestStatistics(PrintStream successPrinter, PrintStream errorPrinter) {
//        printer.println();
        String format = "%s success\n";
        for (Test test : success) {
            printTest(successPrinter, format, test);
        }
        successPrinter.println();
        for (Test test : failure) printTest(errorPrinter, "%s FAILURE\n", test);
        errorPrinter.println();
        for (Map.Entry<Test, Throwable> testExceptionEntry : exception.entrySet())
            errorPrinter.format("%s EXCEPRION\n%s with message: %s\n\n", testExceptionEntry.getKey().getName(), testExceptionEntry.getValue().getClass().getName(), testExceptionEntry.getValue().getMessage());
        errorPrinter.println();
    }

    private void printTest(PrintStream printer, String format, Test test) {
        printer.format(format, test.getName());
        printer.format("execution time: %d ms\n\n", timeRegistrator.getTestExecutionTime(test));
    }

    @Override
    public void onTestStart(Test test) {
        timeRegistrator.onTestStart(test);
    }

    @Override
    public void onTestFinish(Test test) {
        timeRegistrator.onTestFinish(test);
    }
}
